package com.lzx.iteam.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.view.*;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.widget.*;
import com.lzx.iteam.*;
import com.lzx.iteam.bean.WeeklyDataBean;
import com.lzx.iteam.bean.WeeklyDetailListData;
import com.lzx.iteam.emotion.gif.AnimatedGifDrawable;
import com.lzx.iteam.emotion.gif.AnimatedImageSpan;
import com.lzx.iteam.util.*;
import com.lzx.iteam.widget.TextContentView;
import com.lzx.iteam.widget.TextViewSpan;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Megan on 16/5/24.
 */
public class WeeklyDetailListAdapter extends BaseAdapter {

    private Context mContext;
    private ArrayList<WeeklyDetailListData> weeklyDetailListDatas = new ArrayList<WeeklyDetailListData>();
    private String[] s = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二"};
    private String mAction;
    private PopupWindow mPopupWindow;
    private int mPosition = -1;

    public WeeklyDetailListAdapter(Context context, String action) {
        this.mContext = context;
        this.mAction = action;
    }


    public void bindData(ArrayList<WeeklyDetailListData> weeklyDetailListDatas) {
        this.weeklyDetailListDatas = weeklyDetailListDatas;
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return weeklyDetailListDatas == null ? 0 : weeklyDetailListDatas.size();
    }

    @Override
    public Object getItem(int position) {
        return weeklyDetailListDatas == null ? null : weeklyDetailListDatas.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup viewGroup) {
        final ViewHolder holder;
        final WeeklyDetailListData weeklyDetailListData = weeklyDetailListDatas.get(position);
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(mContext).inflate(R.layout.weekly_detail_list_item_layout, null);
            holder.name = (TextView) convertView.findViewById(R.id.tv_weekly_detail_list_item_user_name);
            holder.week = (TextView) convertView.findViewById(R.id.tv_weekly_detail_list_item_week);
            holder.time = (TextView) convertView.findViewById(R.id.tv_weekly_detail_list_item_time);
            holder.img = (ImageView) convertView.findViewById(R.id.iv_weekly_detail_list_item_user_img);
            holder.more = (ImageView) convertView.findViewById(R.id.tv_weekly_detail_list_item_more);
            holder.content = (LinearLayout) convertView.findViewById(R.id.ll_weekly_detail_list_item_content);
            holder.comment = (TextView) convertView.findViewById(R.id.tv_weekly_detail_list_item_comment);
            holder.newComment = (TextView) convertView.findViewById(R.id.tv_weekly_detail_list_item_new_comment_text);
            holder.newCommentLayout = (LinearLayout) convertView.findViewById(R.id.ll_weekly_detail_list_item_new_comment);
            holder.commentLayout = (LinearLayout) convertView.findViewById(R.id.ll_weekly_detail_list_item_comment_list);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.comment.setTag(weeklyDetailListData.weeklyId);

        holder.name.setText(weeklyDetailListData.userName);
        holder.time.setText(DateUtil.getChatTime(Long.parseLong(weeklyDetailListData.createTime) * 1000));
        holder.week.setText(s[Integer.parseInt(weeklyDetailListData.weeklyMonth)] + "月第" + s[Integer.parseInt(weeklyDetailListData.weeklyCount)] + "周(" + DateUtil.formatMonthDay(WeekUtil.getFirstDayOfWeek(WeekUtil.getWeekDateByCount(Integer.parseInt(weeklyDetailListData.weeklyYear), Integer.parseInt(weeklyDetailListData.weeklyMonth), Integer.parseInt(weeklyDetailListData.weeklyCount)))) + "-" + DateUtil.formatMonthDay(WeekUtil.getLastDayOfWeek(WeekUtil.getWeekDateByCount(Integer.parseInt(weeklyDetailListData.weeklyYear), Integer.parseInt(weeklyDetailListData.weeklyMonth), Integer.parseInt(weeklyDetailListData.weeklyCount)))) + ")");
        ImageLoaderInterface.imageLoader.displayImage(weeklyDetailListData.userImg, holder.img, ImageLoaderInterface.optionHeadImage);
        if ("my_weekly".equals(mAction)) {
            holder.more.setVisibility(View.VISIBLE);
        } else {
            holder.more.setVisibility(View.GONE);
        }

        holder.more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View view) {
                //   ((WeeklyDetailListActivity) mContext).showDeleteDialog(weeklyDetailListData.weeklyId, position);

                if (mPosition == position && mPopupWindow.isShowing()){
                    mPopupWindow.dismiss();
                }else{
                    showOperatePop1(view, weeklyDetailListData, position);
                }
                mPosition = position;

            }
        });
        try {
            JSONArray content = new JSONArray(weeklyDetailListData.content);
            holder.content.removeAllViews();
            for (int i = 0; i < content.length(); i++) {
                JSONObject item = content.getJSONObject(i);
                TextContentView contentView = new TextContentView(mContext);
                contentView.setTitleText(item.getString("field"));
                String value = item.getString("value");
                if (!StringUtil.isEmpty(value)) {
                    contentView.setContentText(value.replaceAll("\r", "\r\n"));
                }
                holder.content.addView(contentView);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (weeklyDetailListData.comments != null && weeklyDetailListData.comments.size() > 0) {
            holder.commentLayout.setVisibility(View.VISIBLE);
            holder.commentLayout.removeAllViews();
            for (int i = 0; i < weeklyDetailListData.comments.size(); i++) {
                final Map<String, String> commentMap = weeklyDetailListData.comments.get(i);
                TextView comment = new TextView(mContext);
                comment.setMovementMethod(LinkMovementMethod.getInstance());
                comment.setTextColor(mContext.getResources().getColor(
                        R.color.talk_item_comment_content));
                comment.setTextSize(14);
                String commentName = commentMap.get(Constants.COMMENT_USER_NAME);
                SpannableString commentTo = new SpannableString(commentName);
              /*  TextViewSpan clickableSpan = new TextViewSpan(commentName, mContext, -1, 0);
                clickableSpan.setInfo(commentMap);
                commentTo.setSpan(clickableSpan, 0, commentName.length(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);*/
                ForegroundColorSpan buleSpan = new ForegroundColorSpan(mContext.getResources().getColor(R.color.weekly_comment_name));
                commentTo.setSpan(buleSpan, 0, commentName.length(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                comment.append(commentTo);
                comment.append(":");
                SpannableStringBuilder ssb = handler(comment,
                        commentMap.get(Constants.COMMENT_CONTENT));
                comment.append(ssb.toString().replaceAll("\r", "\r\n"));
                comment.setBackgroundResource(R.color.talk_item_comment_bg);
           /*     comment.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                    }
                });
                comment.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View view) {
                        return true;
                    }
                });*/
                holder.commentLayout.addView(comment);
            }
        } else {
            holder.commentLayout.setVisibility(View.GONE);

        }

        if (holder.comment.getTag() != null) {
            final String tagId = (String) holder.comment.getTag();
            if (!StringUtil.isEmpty(tagId) && tagId.equals(weeklyDetailListData.weeklyId)) {
                holder.comment.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ((WeeklyDetailListActivity) mContext).showBottomLayout(weeklyDetailListData.weeklyId, position);
                    }
                });
            }
        }

        return convertView;
    }

    class ViewHolder {
        TextView name;
        TextView week;
        TextView time;
        ImageView img;
        ImageView more;
        TextView comment;
        TextView newComment;
        LinearLayout content;
        LinearLayout newCommentLayout;
        LinearLayout commentLayout;


    }

    private SpannableStringBuilder handler(final TextView gifTextView, String content) {
        SpannableStringBuilder sb = new SpannableStringBuilder(content);
        String regex = "(\\#\\[face/png/f_static_)\\d{3}(.png\\]\\#)";
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(content);
        while (m.find()) {
            String tempText = m.group();
            try {
                String num = tempText.substring("#[face/png/f_static_".length(), tempText.length() - ".png]#".length());
                String gif = "face/gif/f" + num + ".gif";
                /**
                 * 如果open这里不抛异常说明存在gif，则显示对应的gif
                 * 否则说明gif找不到，则显示png
                 * */
                InputStream is = mContext.getAssets().open(gif);
                sb.setSpan(new AnimatedImageSpan(new AnimatedGifDrawable(is, new AnimatedGifDrawable.UpdateListener() {
                            @Override
                            public void update() {
                                gifTextView.postInvalidate();
                            }
                        })), m.start(), m.end(),
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                is.close();
            } catch (Exception e) {
                String png = tempText.substring("#[".length(), tempText.length() - "]#".length());
                try {
                    int resID = mContext.getResources().getIdentifier(png.split("/")[2].substring(0, png.split("/")[2].indexOf(".")), "drawable", mContext.getApplicationInfo().packageName);
                    sb.setSpan(new ImageSpan(mContext, BitmapFactory.decodeResource(mContext.getResources(), resID)), m.start(), m.end(),
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//                    sb.setSpan(new ImageSpan(mContext, BitmapFactory.decodeStream(mContext.getAssets().open(png))), m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
//                e.printStackTrace();
            }
        }
        return sb;
    }


    /**
     * 弹出操作
     */
    private void showOperatePop(View more, final WeeklyDetailListData weeklyDetailListData, final int position) {
        final View mainView = LayoutInflater.from(mContext).inflate(R.layout.weekly_operate_pop_layout, null);
        LinearLayout edit = (LinearLayout) mainView.findViewById(R.id.ll_weekly_operate_edit);
        LinearLayout delete = (LinearLayout) mainView.findViewById(R.id.ll_weekly_operate_delete);
        ((WeeklyDetailListActivity) mContext).ifShowPopBg(true);
        edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ((WeeklyDetailListActivity) mContext).ifShowPopBg(false);
                mPopupWindow.dismiss();
                if ("my_weekly".equals(mAction)) {
                    Intent intent = new Intent(mContext, WeeklyCreateActivity.class);
                    intent.putExtra("weeklyDetailData", weeklyDetailListData);
                    mContext.startActivity(intent);
                }

            }
        });
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ((WeeklyDetailListActivity) mContext).ifShowPopBg(false);
                mPopupWindow.dismiss();
                ((WeeklyDetailListActivity) mContext).showDeleteDialog(weeklyDetailListData.weeklyId, position);
            }
        });


        int popWidth = Constants.dip2px(mContext, 200);
        //int popHeight = Constants.dip2px(mActivity, 168);
        mPopupWindow = new PopupWindow(mainView,
                popWidth,
                WindowManager.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setOutsideTouchable(true);
        int xOffSet = ((WeeklyDetailListActivity) mContext).getWindowManager().getDefaultDisplay().getWidth() - popWidth - 10;
        int yOffSet = Constants.dip2px(mContext, 10);
        mPopupWindow.setBackgroundDrawable(new ColorDrawable(
                Color.TRANSPARENT));
        mPopupWindow.showAsDropDown(more, xOffSet, -yOffSet);
        AlphaAnimation aa = new AlphaAnimation(0.4f, 1.0f);
        aa.setDuration(250);
        ScaleAnimation sa = new ScaleAnimation(0.2f, 1.0f, 0.2f,
                1.0f, Animation.RELATIVE_TO_SELF, 0.91f,
                Animation.RELATIVE_TO_SELF, 0f);
        sa.setDuration(250);
        AnimationSet set = new AnimationSet(false);
        set.addAnimation(aa);
        set.addAnimation(sa);
        mainView.startAnimation(set);

        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                ((WeeklyDetailListActivity) mContext).ifShowPopBg(false);
            }
        });

    }

    private void showOperatePop1(View v,final WeeklyDetailListData weeklyDetailListData, final int position) {
        //解析菜单view
        View mainView = LayoutInflater.from(mContext).inflate(R.layout.weekly_operate_pop_layout, null);
       // mainView.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.pop_bg_right));
        ((WeeklyDetailListActivity) mContext).ifShowPopBg(true);
        mPopupWindow = new PopupWindow(mainView,ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
        //让弹出框获取焦点（为了让菜单里面的按钮可以点击）
       // window.setFocusable(true);
        //触摸弹出框外面位置，自动dismiss
        mPopupWindow.setBackgroundDrawable(new ColorDrawable());//这句很关键！
        mPopupWindow.setOutsideTouchable(true);
        //显示PopupWindow
//		window.showAsDropDown(v);
        /** 这个很重要 ,获取弹窗的长宽度 */
        mainView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int popupWidth = mainView.getMeasuredWidth();
        int popupHeight = mainView.getMeasuredHeight();
        /** 获取父控件的位置 */
        int[] location = new int[2];
        v.getLocationOnScreen(location);
        /** 显示位置 */
       /* if(location[1]- popupHeight>50){
            mainView.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.bottom_corner_bg));
            window.showAtLocation(v, Gravity.NO_GRAVITY, (location[0] + v.getWidth() / 2) - popupWidth / 2, location[1]
                    - popupHeight);
        }else{
            mainView.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.top_corner_bg));*/
        mPopupWindow.showAsDropDown(v);
        mPopupWindow.setFocusable(true);
      /*  }*/

        mPopupWindow.update();


        //设置menu里面按钮点击监听
        LinearLayout edit = (LinearLayout) mainView.findViewById(R.id.ll_weekly_operate_edit);
        LinearLayout delete = (LinearLayout) mainView.findViewById(R.id.ll_weekly_operate_delete);

        edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ((WeeklyDetailListActivity) mContext).ifShowPopBg(false);
                mPopupWindow.dismiss();
                if ("my_weekly".equals(mAction)) {
                    Intent intent = new Intent(mContext, WeeklyCreateActivity.class);
                    intent.putExtra("weeklyDetailData", weeklyDetailListData);
                    mContext.startActivity(intent);
                }

            }
        });
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ((WeeklyDetailListActivity) mContext).ifShowPopBg(false);
                mPopupWindow.dismiss();
                ((WeeklyDetailListActivity) mContext).showDeleteDialog(weeklyDetailListData.weeklyId, position);
            }
        });
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                ((WeeklyDetailListActivity) mContext).ifShowPopBg(false);
            }
        });


    }



}
